package com.julian.warehouse.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.julian.warehouse.R;
import com.julian.warehouse.dialog.MyAlertDialog;
import com.julian.warehouse.dialog.SPDialogUtils;
import com.julian.warehouse.dialog.SPLoadingDialog;
import com.julian.warehouse.global.Default;
import com.julian.warehouse.interfaces.OnBooleanListener;

import org.json.JSONObject;


/**
 * @author Julian
 *
 */
public abstract class SPBaseActivity extends AppCompatActivity {

	private String TAG = "SPBaseActivity";
	public final int TITLE_HOME = 1;
	public final int TITLE_DEFAULT = 0;
	public final int TITLE_CATEGORY = 2;

	public JSONObject mDataJson;		//包含网络请求所有结果
	public SPLoadingDialog mLoadingDialog;

	private LinearLayout mBackBtn	;
	private TextView mTitleTxtv;
	private OnBooleanListener onBooleanListener;
	public TextView mtvRight;
	public ImageView mivRight;



	/**
	 * activity初始化 //要在子类activity中的setContentView()之后调用
	 * 
	 */
	public void init(){


		//安卓4.4以上才能设置沉浸式布局（状态栏透明覆盖）
		/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			//设置状态栏透明
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//重新设置顶部tab栏高度（以适配顶部的状态栏）
			LinearLayout pageHead = (LinearLayout) findViewById(R.id.page_head);
			if(pageHead!=null){
				android.view.ViewGroup.LayoutParams params =  pageHead.getLayoutParams();
				params.height=(int)PixelUtil.dp2px(70);
				pageHead.setLayoutParams(params);
			}
		}*/

		mBackBtn = (LinearLayout)findViewById(R.id.back);
		mTitleTxtv = (TextView)findViewById(R.id.mtitle);

		mtvRight = (TextView)findViewById(R.id.tv_share);
		mivRight = (ImageView)findViewById(R.id.right);

		initView();
		initData();
		initEvent();
	}


	/**
	 * 设置标题tab栏，子类activity的xml布局中要include page_head
	 *
	 */

	public void setHeadTitle(String title){

		//不显示返回箭头跟右边按钮,参数为string

		if(mBackBtn!=null)mBackBtn.setVisibility(View.GONE);


		if (title!=null)mTitleTxtv.setText(title);
		mtvRight.setVisibility(View.GONE);
	}

	public void setHeadTitle(int titleId){

		//不显示返回箭头跟右边按钮,参数为id

		if(mBackBtn!=null)mBackBtn.setVisibility(View.GONE);
		mTitleTxtv.setText(getResources().getString(titleId));
		mtvRight.setVisibility(View.GONE);
	}


	public void setHeadTitle(boolean backShow, String title){

	    //是否显示返回箭头
		if (backShow){
			mBackBtn.setVisibility(View.VISIBLE);
			mBackBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					SPBaseActivity.this.finish();
					overridePendingTransition(R.anim.left_to_right,R.anim.to_right);
				}
			});
		}else{
			if(mBackBtn!=null)mBackBtn.setVisibility(View.GONE);
		}

		if (title!=null)mTitleTxtv.setText(title);
		mtvRight.setVisibility(View.GONE);
	}


	public void setHeadTitle(boolean backShow, String title, boolean rightShow){

		//是否显示返回箭头
		if (backShow){
			mBackBtn.setVisibility(View.VISIBLE);
			mBackBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					SPBaseActivity.this.finish();
					overridePendingTransition(R.anim.left_to_right,R.anim.to_right);
				}
			});
		}else{
			if(mBackBtn!=null)mBackBtn.setVisibility(View.GONE);
		}

		if (title!=null)mTitleTxtv.setText(title);

		if(rightShow){
			mtvRight.setVisibility(View.VISIBLE);
		}else {
			mtvRight.setVisibility(View.GONE);
		}

	}





	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		Default.currentContext = this;

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public void bindClickListener(View v , View.OnClickListener listener){
		if(v != null && listener != null){
			v.setOnClickListener(listener);
		}

	}


	public void showToast(String msg){
		SPDialogUtils.showToast(this, msg);
	}

	public void showToast(int id) {
		SPDialogUtils.showToast(this, getResources().getString(id).toString());
	}







	public void showLoadingToast(){
		showLoadingToast(null);
	}

	public void showLoadingToast(String title){
		mLoadingDialog = new SPLoadingDialog(this , title);
		mLoadingDialog.setCanceledOnTouchOutside(false);
		mLoadingDialog.show();
	}

	public void hideLoadingToast(){
		if(mLoadingDialog !=null){
			mLoadingDialog.dismiss();
		}
	}



	/**
	 * 以下三个函数不需要再子类调用, 只需要在子类的
	 * onCrate()中调用:super.init()方法即可
	 * 基类函数,初始化界面
	 */
	abstract public void initView();
	
	/**
	 * 基类函数, 初始化数据
	 */
	abstract public void initData();
	
	/**
	 * 基类函数, 绑定事件
	 */
	abstract public void initEvent();

	/**
	 * 处理网络加载过的数据
	 */
	public void dealModel(){}




	protected void showAlert(String msg) {

		showMyDialog(true, msg, "确定", new MyAlertDialog.OnMyClickListener() {

			@Override
			public void onClick(MyAlertDialog dialog) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});


	}



	protected void showAlertThenFinish(String msg) {

		showMyDialog(false, msg, "确定", new MyAlertDialog.OnMyClickListener() {

			@Override
			public void onClick(MyAlertDialog dialog) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				finish();
			}
		});



	}


	protected void showConfirm(String msg, final Intent intent) {

		showMyDialog(true, msg, "确定", new MyAlertDialog.OnMyClickListener() {

			@Override
			public void onClick(MyAlertDialog dialog) {
				// TODO Auto-generated method stub
				dialog.dismiss();
				startActivity(intent);
				//第一个参数是目标页进入动画，第二个参数是本页结束动画
				overridePendingTransition(R.anim.right_to_left, R.anim.to_left);
			}
		},"取消", new MyAlertDialog.OnMyClickListener() {

			@Override
			public void onClick(MyAlertDialog dialog) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});


	}





	//万能dialog--按钮数1-3
	public void showMyDialog(boolean cancelable, String msg, String posBtnName, final MyAlertDialog.OnMyClickListener posListener) {

		final  MyAlertDialog dialog = new MyAlertDialog(this);
		dialog.setTitle(R.string.systemNotify);
		dialog.setMessage(msg);
		dialog.setCancelable(cancelable);
		if(posListener!=null)dialog.setPositiveButton(posBtnName,posListener);

	}



	public void showMyDialog(boolean cancelable, String msg, String posBtnName, final MyAlertDialog.OnMyClickListener posListener, String negBtnName, final MyAlertDialog.OnMyClickListener negListener) {
		final  MyAlertDialog dialog = new MyAlertDialog(this);
		dialog.setTitle(R.string.systemNotify);
		dialog.setMessage(msg);
		dialog.setCancelable(cancelable);
		if(posListener!=null)dialog.setPositiveButton(posBtnName,posListener );//确定按钮
		if(negListener!=null)dialog.setNegativeButton(negBtnName,negListener);//取消按钮

	}


	public void showMyDialog(boolean cancelable, String msg, String posBtnName, final MyAlertDialog.OnMyClickListener posListener, String centerBtnName, final MyAlertDialog.OnMyClickListener centerListener, String negBtnName, final MyAlertDialog.OnMyClickListener negListener) {
		final  MyAlertDialog dialog = new MyAlertDialog(this);
		dialog.setTitle(R.string.systemNotify);
		dialog.setMessage(msg);
		dialog.setCancelable(cancelable);
		if(posListener!=null)dialog.setPositiveButton(posBtnName,posListener);//确定按钮
		if(centerListener!=null)dialog.setNeutralButton(centerBtnName,centerListener);//中间按钮
		if(negListener!=null)dialog.setNegativeButton(negBtnName,negListener);//取消按钮

	}


	@Override
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.right_to_left,R.anim.to_left);
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		super.startActivityForResult(intent, requestCode);
		overridePendingTransition(R.anim.right_to_left,R.anim.to_left);
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.left_to_right,R.anim.to_right);
	}



	public void requestPermission(String[] permissions, OnBooleanListener onBooleanListener) {
		this.onBooleanListener = onBooleanListener;

		boolean isMinSdkM = Build.VERSION.SDK_INT < Build.VERSION_CODES.M;
		if (isMinSdkM || permissions.length == 0) {
			onBooleanListener.onClick(true,new int[]{});
			return;
		}

		boolean isAlreadyHave=true;

		for (int i=0;i<permissions.length;i++){
			int permission = ContextCompat.checkSelfPermission(this,
					permissions[i]);
			if (permission != PackageManager.PERMISSION_GRANTED){
				isAlreadyHave=false;
				break;
			}
		}

		if (isAlreadyHave){
			onBooleanListener.onClick(true,new int[]{});
		}else {
			ActivityCompat.requestPermissions(this, permissions, 1);
		}

	}



	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		int[] res =new int[permissions.length];

		for (int i = 0; i < grantResults.length; i++) {
			boolean isTip = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
			if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
				if (isTip) {//表明用户没有彻底禁止弹出权限请求
					//requestPermission(PermissionHelper.getInstance().filterPermissions(permissions));
					//String s = permissions[i];
					//ActivityCompat.requestPermissions(this, new String[]{s}, 1);


				} else {//表明用户已经彻底禁止弹出权限请求
					   //PermissionMonitorService.start(this);//这里一般会提示用户进入权限设置界面
					showToast("请手动去系统应用权限管理中开启本应用的相关权限！");

				}

				res[i]=0;

			}else {
				res[i]=1;
			}
		}

		boolean allHave=true;
		for (int j=0;j<res.length;j++){
			if (res[j]==0){
				allHave=false;
				break;

			}
		}

		onBooleanListener.onClick(allHave,res);

	}
	
}
